<?php
	//$Id: run.php 383 2009-03-03 06:38:10Z cameron.bracken $
	
	// run.php: 
	// Creates a file for this run cantaining key/vaue pairs for the submitted 
	// 	input form that is the form: runs/pondsim-input-<unix time stamp>
	//	
	
	include('sandbox/www/vars.php');
	
	// create the file name
	$t=time();
	$fn = "$runsdir/pondsim-input-".$t;
	$outfile=fopen($fn,'w');
	
	// loop thorugh keys and write key,value
    foreach($_GET as $key => $value){ 
    	if($key == 'rundes'){
  			// write the run description with a date stamp and the name of the run file
    		$d = $value.': '.date("D F d Y h:i:s A",$t)."\n";
    		fwrite($outfile, $d);
    		fwrite($outfile, "loaded_run_file,$fn\n");
    		fwrite($outfile, "loaded_time,$t\n");
    	}else{
    		//write the rest of the keys
			fwrite($outfile, "$key,$value\n");
        }
    } 
    fclose($outfile);
   
	// Make the nely created run file active
	system("Rscript R/load-run.R $fn");
   
    //Clean up the pondSim run directory 
    system('rm sandbox/pondSim/*');
    
    //Make a new copy of the executable and the plotting script
    system('cp pondSim/pondSim.bargraph.R sandbox/pondSim/pondSim.bargraph.R');
    system('cp pondSim/pondSim sandbox/pondSim/pondSim');
    
    //create a new input file
	system("Rscript R/prep-pondsim-input.R $fn");
	
	//Run the model
	chdir('sandbox/pondSim/');
		system('./pondSim');
		system('Rscript pondSim.bargraph.R');
		system("cp barplot.png ../output/img/barplot-$t.png");
		system("cp barplot.pdf ../output/img/barplot-$t.pdf");
		system("cp pondSim.output ../output/data/pondSim-$t.output");
		system("cp pondSim.log ../output/logs/pondSim-$t.log");
	chdir('../../');

    
    
    // redirect to the results page
    header("Location: results.php?runfile=$fn&time=$t");
?>
